import { useEffect, useRef } from "react";

import "./index.scss";
function XtxInfiniteLoading({
  loading,
  finished,
  infinit,
}: {
  loading: boolean;
  finished: boolean;
  infinit: () => void;
}) {
  const target = useRef<HTMLImageElement | null>(null);
  useEffect(() => {
    const observer = new IntersectionObserver(
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          if (!loading && !finished) {
            console.log("进入可视区");

            infinit();
          }
        }
      },
      { threshold: 0.5 }
    );
    if (target.current) {
      observer.observe(target.current); // 观察图片 DOM 元素
    }

    return () => {
      if (target.current) {
        observer.unobserve(target.current); // 在组件卸载时取消观察
      }
    };
  }, [finished, loading]);
  return (
    <div className="xtx-infinite-loading" ref={target}>
      {loading && (
        <div className="loading">
          <span className="img"></span>
          <span className="text">正在加载...</span>
        </div>
      )}
      {finished && (
        <div className="none">
          <span className="img"></span>
          <span className="text">亲，没有更多了</span>
        </div>
      )}
    </div>
  );
}

export default XtxInfiniteLoading;
